package com.flying.wbp.controller;

import com.flying.wbp.storage.StorageFileNotFoundException;
import com.flying.wbp.storage.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api")
public class FileUploadController {

    private final StorageService storageService;

    @Autowired
    public FileUploadController(StorageService storageService) {
        this.storageService = storageService;
    }

    @GetMapping("download/{filename:.+}")
    public Resource serveFile(@PathVariable String filename, HttpServletResponse response) {
        Resource file = storageService.loadAsResource(filename);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"");
        return file;
    }

    @PostMapping("upload")
    public void handleFileUpload(@RequestParam("file") MultipartFile file) {
        storageService.store(file);
    }

    @ExceptionHandler(StorageFileNotFoundException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public void handleStorageFileNotFound(StorageFileNotFoundException exc) {
    }
}